//
//  TTDiscoverArticleViewController.m
//  Adorable_Things
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "TTDiscoverArticleViewController.h"
#import "TTDiscoverArticleMainTableViewCell.h"
#import "TTDiscoverArticleModel.h"
#import "ArticleDetailViewController.h"
#import "ArticleDetailMengwenViewController.h"
#import "ATLoginViewController.h"

#define kArticleUrl @"http://api.menghuoapp.com/v1/post/list"

@interface TTDiscoverArticleViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataArr;

@end

@implementation TTDiscoverArticleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _page_size = 20;
    _page = 0;
    _order_dir = 0;
    _order_by = 0;
    
    _dataArr = [NSMutableArray array];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 300;
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-568h@2x"]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    // 进入刷新状态后会自动调用这个block
      _page = 0;
      [self setUpData];
    }];
    // 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _page += 1;
        [self setUpData];
    }];
    
}

- (void)setUpData
{
    ATUserManager *atManager = [ATUserManager shareManager];
    
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"page"] = [NSString stringWithFormat:@"%ld", (long)_page];
    parDic[@"page_size"] = [NSString stringWithFormat:@"%ld", (long)_page_size];
    parDic[@"order_dir"] = self.order_dir;
    parDic[@"order_by"] = self.order_by;
    parDic[@"auth_token"] = atManager.auth_token;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:kArticleUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataArray = responseObject[@"data"];
        if (_page == 0) {
            [_dataArr removeAllObjects];
        }
        for (NSDictionary *oneDic in dataArray) {
            TTDiscoverArticleModel *model = [[TTDiscoverArticleModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_dataArr addObject:model];
        }
        NSLog(@"%lu", (unsigned long)_dataArr.count);
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [_tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDiscoverArticleMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TTDiscoverArticleMainTableViewCell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"TTDiscoverArticleMainTableViewCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    TTDiscoverArticleModel *model = _dataArr[indexPath.row];
    self.albumID = model.post_id;
    cell.titleLabel.text = model.title;
    cell.subTitleLabel.font = [UIFont systemFontOfSize:14];
    cell.subTitleLabel.textColor = [UIColor lightGrayColor];
    cell.subTitleLabel.text = model.subtitle;
    [cell.favorButton addTarget:self action:@selector(favorButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.favorButton setTintColor:[UIColor lightGrayColor]];
    if ([model.favorite integerValue] == 0) {
        [cell.favorButton setImage:[UIImage imageNamed:@"iconfont-tubiao"] forState:(UIControlStateNormal)];
    }else {
        [cell.favorButton setImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
        cell.favorButton.tintColor = [UIColor redColor];
    }
    [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:model.pic_url]];
    cell.favorNumLabel.text = [NSString stringWithFormat:@"%@", model.favorite_num];
    cell.favorNumLabel.textAlignment = NSTextAlignmentRight;
    cell.favorNumLabel.font = [UIFont systemFontOfSize:14];
    cell.favorNumLabel.textColor = [UIColor lightGrayColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArticleDetailViewController *articleDetailVC = [[ArticleDetailViewController alloc] init];
    TTDiscoverArticleModel *model = _dataArr[indexPath.row];
    articleDetailVC.ID = model.post_id;
    articleDetailVC.model = model;
    self.tabBarController.tabBar.hidden = YES;
    articleDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:articleDetailVC animated:YES];
}

- (void)favorButtonAction:(UIButton *)button
{
    ATUserManager *manager = [ATUserManager shareManager];
    if (manager.isLogin == 0) {
        ATLoginViewController *loginVC = [[ATLoginViewController alloc] init];
        UINavigationController *loginNavC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        loginNavC.navigationBarHidden = YES;
        [self presentViewController:loginNavC animated:YES completion:nil];
    } else{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth_token"] = manager.auth_token;
    parDic[@"post_id"] = self.albumID;
    TTDiscoverArticleMainTableViewCell *cell = (TTDiscoverArticleMainTableViewCell *)[[button superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    TTDiscoverArticleModel *model = _dataArr[indexPath.row];
    if ([model.favorite integerValue] == 0) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:@"http://api.menghuoapp.com/v1/post/mark" parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"收藏成功");
            [cell.favorButton setImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
            cell.favorButton.tintColor = [UIColor redColor];
            model.favorite = [NSNumber numberWithInt:1];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];
    } else {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:@"http://api.menghuoapp.com/v1/post/unmark" parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"取消成功");
            [cell.favorButton setImage:[UIImage imageNamed:@"iconfont-tubiao"] forState:(UIControlStateNormal)];
            cell.favorButton.tintColor = [UIColor lightGrayColor];
            model.favorite = [NSNumber numberWithInt:0];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];
      }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _page_size = _page_size * (self.page + 1);
    self.page = 0;
    [_dataArr removeAllObjects];
    [self setUpData];
    self.page = _page_size / 20 - 1;
    self.page_size = 20;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
